﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Crank.Core
{
    public class InflectingModelTransormer : IModelTransformer
    {
        #region Blackboard Variables

        private static readonly IProperty<NounSpace> Nouns = Blackboard.Create<NounSpace>("Nouns");

        #endregion

        #region IModelTransformer Members

        public void ApplyTransform(DataModel target)
        {
            var entityNames = target.Entities.Keys.ToArray<string>();

            Nouns.Value = NounSpace.FromWordList(entityNames);

            foreach (string entityName in entityNames)
            {
                if (! Nouns.Value.IsPlural(entityName))
                {
                    var pluralName = Nouns.Value.PluralOf(entityName);
                    var singularEntity = target.GetEntityByName(entityName);
                    var pluralEntity = target.GetEntityByName(pluralName);
                    foreach (AttributeDef att in singularEntity.Attributes)
                    {
                        pluralEntity.Attributes.Add(att);
                    }
                    foreach (LinkDef link in target.Links)
                    {
                        if (link.LHS == singularEntity)
                            link.LHS = pluralEntity;
                        if (link.RHS == singularEntity)
                            link.RHS = pluralEntity;
                    }
                    target.Entities.Remove(entityName);
                }
            }
        }

        #endregion
    }
}
